/**
 * Created by jiexin on 2017/9/19.
 */
layui.use(['form', 'element', 'layer', 'table'], function() {
    var form = layui.form;
    var element = layui.element;
    var table = layui.table;
    var $ = layui.jquery;
    var layer = layui.layer; //弹层

    var perendall = document.getElementById("perend");
    if (perendall.offsetHeight > 300){
        $(".perip").css("min-height", perendall.offsetHeight - 220 + 'px');
        // $("#perplayip").css("min-height", perendall.offsetHeight - 220 + 'px');
        $(".layui-form-item-hosts").css("margin-bottom", "10px")
    }

    var shell_group_select = {};
    var play_group_select = {};
    var play_yaml_select = {};

    for (var i=0; i < group_list.length; i++) {
        $(".perlist").append('<option value="'+ i + '">' + group_list[i]["group_name"] + '</option>');
        // $("#perplaylist").append('<option value="'+ i + '">' + group_list[i]["group_name"] + '</option>');
        var modify_list_shell = {};
        var modify_list_play = {};
        $.each(group_list[i], function (k,v) {
            modify_list_shell[k] = v;
            modify_list_play[k] = v
        });
        shell_group_select[i] = modify_list_shell;
        play_group_select[i] = modify_list_play;
    }

    for (var n=0; n < yaml_list.length; n++) {
        $("#perplaybook").append('<option value="'+ n + '">' + yaml_list[n]["yaml_name"] + '</option>');
        play_yaml_select[n] = yaml_list[n]
    }

    $(".perkey").val(group_list[0]["group_key"]);
    // $("#perplaykey").val(group_list[0]["group_key"]);
    $(".perip").val(host_list(group_list[0]["group_host"]));
    // $("#perplayip").val(host_list(group_list[0]["group_host"]));

    function host_list(listdata) {
        var txt = "";
        for(var i=0; i < listdata.length; i++){

            if (i === 0){
                txt = txt + listdata[i]
            }else{
                txt = txt  + ',' + listdata[i]
            }
        }
        return txt
    }
    form.render('select');

    form.on(['select(perlist)'], function(data){
        var index_id = data.value;
        var selectdata = shell_group_select[index_id];
        $("#perkey").val(selectdata["group_key"]);
        $("#perip").val(host_list(selectdata["group_host"]));
    });

    form.on('select(perplaylist)', function(data){
        var index_id = data.value;
        var selectdata = play_group_select[index_id];
        $("#perplaykey").val(selectdata["group_key"]);
        $("#perplayip").val(host_list(selectdata["group_host"]));
    });
    //
    form.on('select(perrulelist)', function(data){
        var index_id = data.value;
        var selectdata = play_group_select[index_id];
        $("#perrulekey").val(selectdata["group_key"]);
        $("#perruleip").val(host_list(selectdata["group_host"]));
    });


    //执行调用
    function ajaxperform(pdata) {
        $.ajax({
             url: '/yaml-start-perform/',
             dataType: 'json',
             type: 'POST',
             data: pdata,
             success: function (returnshelldata) {
                 if (returnshelldata["status"] === 0){
                     $("#returnstatus").val(returnshelldata["r_data"])
                 }else{
                     layer.msg("执行失败，请检查！")
                 }
             }
         })
    }

     form.on('submit(performshell)', function(sdata){
         var shelldata = sdata.field;
         var sendshelldata = shell_group_select[shelldata["perlist"]];
         sendshelldata["cmd"] = shelldata["pershell"];
         sendshelldata["type"] = shelldata["ansibletype"];
         var s_data = {"data": JSON.stringify(sendshelldata), "type": "shell"};
         ajaxperform(s_data)
     });

     form.on('submit(performpaly)', function(pdata){
         var playdata = pdata.field;
         var sendpalydata = play_group_select[playdata["perplaylist"]];
         sendpalydata["yaml_id"] = play_yaml_select[playdata["perplaybook"]]["yaml_id"];
         sendpalydata["playval"] = playdata["perpalyval"];
         var p_data = {"data": JSON.stringify(sendpalydata), "type": "playbook"};
         ajaxperform(p_data);
     });

     form.on('submit(performrule)', function(sdata){
         var shelldata = sdata.field;
         var sendshelldata = shell_group_select[shelldata["perrulelist"]];
         sendshelldata["tag"] = shelldata["perruletag"];
         sendshelldata["file"] = shelldata["perrulefile"];
         sendshelldata["val"] = shelldata["perruleval"];
         console.log(sendshelldata);
         var r_data = {"data": JSON.stringify(sendshelldata), "type": "rule"};
         ajaxperform(r_data);
     });


     //历史记录
    var sel_div = "shelltb";
    var play_data = [];
    var rule_data = [];
    var shell_list= [];
    form.on('select(typeselect)', function(data){
        var p_data = {"type":data.value};
        ajaxFive(p_data);
        if (data.value === "1"){
            $("#"+ sel_div).addClass("layui-hide");
            sel_div = "shelltb";
            $("#shelltb").removeClass("layui-hide");
        }else if (data.value === "2"){
            $("#"+ sel_div).addClass("layui-hide");
            sel_div = "playbooktb";
            $("#playbooktb").removeClass("layui-hide")
        }else if (data.value === "3"){
            $("#"+ sel_div).addClass("layui-hide");
            sel_div = "ruletb";
            $("#ruletb").removeClass("layui-hide")
        }
    });

    function ajaxFive(pdata) {
        $.ajax({
             url: '/yaml-history/',
             dataType: 'json',
             type: 'POST',
             data: pdata,
             success: function (Fdata) {
                 if (Fdata["status"] === 0){
                     if (pdata["type"] === "1"){
                        shelltable.reload({
                            data: Fdata["data"]
                        })
                     }else if (pdata["type"] === "2"){
                        playtable.reload({
                            data: Fdata["data"]
                        })
                     }else if (pdata["type"] === "3"){
                        ruletable.reload({
                            data: Fdata["data"]
                        })
                     }
                 }
             }
         })
    }

    var performa = document.getElementById("alltb");
    var p_h = performa.offsetHeight - 10;
    var p_w = performa.offsetWidth - 10;
    console.log(p_h,p_w);



    // {"exe_user":"aa", "exe_group":"bb", "exe_shell":"cc", "createDate":"dd"}

    var table_format_shell = [[
         {field: 'exe_user', align: 'center', title: '操作人', width: "20%"}
         , {field: 'exe_group', title: '服务器', width: "40%"}
         , {field: 'createDate', title: '时间', width: "25%"}
         , {fixed: 'right',width: "20%", align: 'center',  title: '操作', toolbar: '#shellDemo'}
    ]];

    $('.layui-table-shell').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        //var tableid = document.getElementById('update').id;
        createtables(etaleid,tableid,shell_list,table_format_shell,p_h);
        shelltool(toolid,tableid);
    });

    var shelltable;
    function createtables(etaleid,tableid,datas,table_format,table_height) {
        shelltable = table.render({
            elem: etaleid,
            id: tableid,
            height: table_height,
            limit: 10,
            page: true,
            data: datas,
            cols: table_format
        });
    }

    function shelltool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);

            //tr.index()
            if (layEvent === 'check') {
                var txt = "执行命令：" + data["exe_shell"] + "\n" + "执行返回：" + "\n" + data["exe_results"];
                $("#returnstatus").val(txt)
            }
        })
    }
    //
    var table_format_play = [[
         {field: 'exe_user', align: 'center', title: '操作人', width: "20%"}
         , {field: 'exe_group', title: '服务器', width: "40%"}
         , {field: 'createDate', title: '时间', width: "25%"}
         , {fixed: 'right',width: "20%", align: 'center',  title: '操作', toolbar: '#palyDemo'}
    ]];
    //
    $('.layui-table-play').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        //var tableid = document.getElementById('update').id;
        createtablep(etaleid,tableid,play_data,table_format_play,p_h);
        playtool(toolid,tableid);
    });

    var playtable;
    function createtablep(etaleid,tableid,datas,table_format,table_height) {
        playtable = table.render({
            elem: etaleid,
            id: tableid,
            height: table_height,
            limit: 10,
            page: true,
            data: datas,
            cols: table_format
        });
    }

    function playtool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);

            //tr.index()
            if (layEvent === 'check') {
                var txt = "文件名称：" + data["exe_playbook"] + "\n" + "变量参数：" + data["exe_value"] + "\n" +"执行返回：" + "\n" + data["exe_results"];
                $("#returnstatus").val(txt)
            }
        })
    }
    //
    var table_format_rule = [[
         {field: 'exe_user', align: 'center', title: '操作人', width: "20%"}
         , {field: 'exe_group', title: '服务器', width: "40%"}
         , {field: 'createDate', title: '时间', width: "25%"}
         , {fixed: 'right',width: "20%", align: 'center',  title: '操作', toolbar: '#ruleDemo'}
    ]];

    $('.layui-table-rule').each(function() {
        //获取标签对于的一个属性
        var $obj = $(this);
        var tableid = $obj[0].id;
        var etaleid = '#' + tableid;
        var toolid = 'tool(' + tableid + ')';
        //var tableid = document.getElementById('update').id;
        createtabler(etaleid,tableid,rule_data,table_format_rule,p_h);
        ruletool(toolid,tableid);
    });

    var ruletable;
    function createtabler(etaleid,tableid,datas,table_format,table_height) {
        ruletable = table.render({
            elem: etaleid,
            id: tableid,
            height: table_height,
            limit: 10,
            page: true,
            data: datas,
            cols: table_format
        });
    }

    function ruletool(toolid, tableid) {
        //监听工具条
        //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        table.on(toolid, function (obj) {
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值
            var tr = obj.tr; //获得当前行 tr 的DOM对象
            var checkStatus = table.checkStatus(tableid);

            //tr.index()
            if (layEvent === 'check') {
                var txt = "文件名称：" + data["exe_rule_file"] + "\n" + "变量参数：" + data["exe_value"] + "\n" + "标签：" + data["exe_rule"] + "\n" +"执行返回：" + "\n" + data["exe_results"];
                $("#returnstatus").val(txt)
            }
        })
    }
    ajaxFive({"type":"1"});



    $('.demoTable .layui-btn').on('click', function() {
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

});